<?php

namespace App\Services;


use extend\services\nailin\NewdemandService;
use Illuminate\Support\Facades\Log;

/**
 * 金蝶相关服务
 * Class kingDeeService
 * @package extend\services\nailin
 */
class KingDeeService
{

    protected $kingDee;
    private $formId = '';
    private $fields = '';
    private $where = '';
    private $order = '';
    private $startRow = 0;
    private $topRowCount = 0;
    private $limit = 0;
    private $subSystemId = '';
    private $saveData = [];
    private $unAuditData = [];
    private $deleteData = [];

    public function __construct()
    {
        $this->kingDee = new NewdemandService();
        $this->resetParam();
        $this->resetSaveData();
    }

    /**
     * 查询参数初始化
     */
    private function resetParam(){
        //$this->formId = '';
        $this->fields = '';
        $this->where = '';
        $this->order = '';
        $this->startRow = 0;
        $this->topRowCount = 0;
        $this->limit = 0;
        $this->subSystemId = '';
    }

    /**
     * 初始化单据保存公共头信息
     */
    private function resetSaveData(){

        $this->saveData = [
            'NeedUpDateFields' => [],
            'NeedReturnFields' => [],
            'IsDeleteEntry' => "true",
            'SubSystemId' => "",
            'IsVerifyBaseDataField' => "false",
            'IsEntryBatchFill' => "true",
            'ValidateFlag' => "true",
            'NumberSearch' => "true",
            'IsAutoAdjustField' => "false",
            'InterationFlags' => "",
            'IgnoreInterationFlag' => "",
            'IsControlPrecision' => "false",
            'ValidateRepeatJson' => "false",
            'Model' => []
        ];

    }

    /**
     * 初始化反审数据
     */
    private function initUnAuditData(){
        $this->unAuditData = [];
    }

    /**
     * 接口名称设置
     * @param $form
     * @return $this
     */
    public function form($form){
        $this->formId = $form;
        return $this;
    }

    /**
     * 指定查询字段
     * @param $fields
     * @return $this
     */
    public function field($fields){
        $this->fields = $fields;
        return $this;
    }

    /**
     * 指定查询条件
     * @param $key
     * @param $val
     * @param string $option
     * @return $this
     */
    public function where($key,$val,$option = '='){
        $this->where .= "and {$key} {$option} '$val'";
        return $this;
    }
    /**
     * 排序
     * @param $order
     * @return $this
     */
    public function order($order){
        $this->order = $order;
        return $this;
    }

    public function startRow($row){
        $this->startRow = $row;
        return $this;
    }

    public function topRowCount($row){
        $this->topRowCount = $row;
        return $this;
    }

    public function limit($limit){
        $this->limit = $limit;
        return $this;
    }

    public function subSystemId($subSystemId){
        $this->subSystemId = $subSystemId;
        return $this;
    }

    /**
     * 查询参数格式整理
     * @return array
     * @throws \Exception
     */
    private function getQueryArray(){

        if($this->formId == ''){
            throw new \Exception('金蝶单据查询formId参数不能为空');
        }

        if($this->fields == ''){
            throw new \Exception('金蝶单据查询field参数不能为空');
        }

        return [
            'FormId'        => $this->formId,
            'FieldKeys'     => trim($this->fields),
            'FilterString'  => trim($this->where,'and '),
            'OrderString'   => $this->order,
            'TopRowCount'   => $this->topRowCount,
            'StartRow'      => $this->startRow,
            'Limit'         => $this->limit,
            'SubSystemId'   => $this->subSystemId,
        ];
    }

    /**
     * list转换键值对
     * @param $list
     * @param $fields
     * @return array
     */
    private function listToArray($list,$fields){

        if(empty($list)) return [];

        $fields = explode(',',$fields);

        $newList = [];
        foreach ($list as $key => $val){
            foreach ($val as $itemKey => $itemVal){
                $newList[$key][$fields[$itemKey]] = $itemVal;
            }
        }
        return $newList;
    }

    /**
     * 单据查询
     * @throws \Exception
     */
    public function ExecuteBillQuery(){

        $queryData = $this->getQueryArray();

        $postData = $this->kingDee->create_postdata([$queryData]);
        $result = $this->kingDee->ExecuteBillQuery($this->kingDee->cloudUrl,$postData);

        if(empty($result)) throw new \Exception('金蝶响应错误，接口返回为空');
        $result = json_decode($result,true);

        if(isset($result[0]['0']['Result']['ResponseStatus']['ErrorCode']) && isset($result[0]['0']['Result']['ResponseStatus']['Errors'][0]['Message'])){
            throw new \Exception('金蝶API报错：' . $result[0]['0']['Result']['ResponseStatus']['Errors'][0]['Message']);
        }

        $arr = $this->listToArray($result,$this->fields);
        $this->resetParam();

        return $arr;
    }

    /**
     * 单据推送（保存）
     * @param $data
     * @return $head 头部公共信息
     */
    public function invokeSave($data,$head = null){

        $postData = $this->getSaveArray($data,$head);

        Log::info("金蝶单据推送【{$this->formId}】：\r\n" . json_encode($postData));

        //调用金蝶单据保存接口
        $result = $this->kingDee->invoke_save($this->formId,$postData);

        Log::info("金蝶单据推送回执【{$this->formId}】：\r\n" . $result);

        if(empty($result)) throw new \Exception('金蝶响应错误，接口返回为空');
        $result = json_decode($result,true);

        if(!$result['Result']['ResponseStatus']['IsSuccess']){
            throw new \Exception('金蝶单据推送报错：' . $result['Result']['ResponseStatus']['Errors'][0]['Message']);
        }

        return $result;

    }

    /**
     * 拼接单据保存参数
     * @param $data Model 参数
     * @return $head 头部公共信息 array()
     */
    private function getSaveArray($data,$head=null){

        if($this->formId == ''){
            throw new \Exception('金蝶单据查询formId参数不能为空');
        }

        if(!empty($head)){

            if(isset($head['NeedUpDateFields'])){
                $this->saveData['NeedUpDateFields'] = $head['NeedUpDateFields'];
            }

        }

        $this->saveData['Model'] = $data;

        return $this->saveData;
    }

    /**
     * 反审单据
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    public function unAudit($data){
        $postData = $this->getUnAuditData($data);

        Log::info("金蝶单据反审推送【{$this->formId}】：\r\n" . json_encode($postData));

        $result = $this->kingDee->invoke_unaudit($this->formId,$postData);

        Log::info("金蝶单据反审回执【{$this->formId}】：\r\n" . $result);

        if(empty($result)) throw new \Exception('金蝶响应错误，接口返回为空');
        $result = json_decode($result,true);

        if(!$result['Result']['ResponseStatus']['IsSuccess']){

            if(mb_strpos($result['Result']['ResponseStatus']['Errors'][0]['Message'],'数据状态为创建或重新审核状态，反审核失败，请先提交、审核') !== false){
                return true;
            }

            throw new \Exception('金蝶单据反审报错：' . $result['Result']['ResponseStatus']['Errors'][0]['Message']);
        }

        return $result;

    }

    /**
     * 获取反审提交数据
     * @param $data
     * @throws \Exception
     */
    private function getUnAuditData($data){
        if($this->formId == ''){
            throw new \Exception('金蝶单据formId参数不能为空');
        }

        if(empty($data)){
            throw new \Exception('提交参数不能为空');
        }

        $postData = [
            'CreateOrgId'           => 0,
            'Numbers'               => is_string($data) ? [$data] : $data,
            'Ids'                   => "",
            'InterationFlags'       => '',
            'IgnoreInterationFlag'  => '',
            'NetworkCtrl'           => '',
            'IsVerifyProcInst'      => ''
        ];

        return $postData;

    }

    /**
     * 删除单据
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    public function delete($data){
        $postData = $this->getUnAuditData($data);

        Log::info("金蝶单据删除推送【{$this->formId}】：\r\n" . json_encode($postData));

        $result = $this->kingDee->invoke_delete($this->formId,$postData);

        Log::info("金蝶单据删除回执【{$this->formId}】：\r\n" . $result);

        if(empty($result)) throw new \Exception('金蝶响应错误，接口返回为空');
        $result = json_decode($result,true);

        if(!$result['Result']['ResponseStatus']['IsSuccess']){
            throw new \Exception('金蝶单据删除报错：' . $result['Result']['ResponseStatus']['Errors'][0]['Message']);
        }

        return $result;

    }

    /**
     * 获取删除提交数据
     * @param $data
     * @throws \Exception
     */
    private function getDeleteData($data){
        if($this->formId == ''){
            throw new \Exception('金蝶单据formId参数不能为空');
        }

        if(empty($data)){
            throw new \Exception('提交参数不能为空');
        }

        $postData = [
            'CreateOrgId'           => 0,
            'Numbers'               => is_string($data) ? [$data] : $data,
            'Ids'                   => "",
            'NetworkCtrl'           => ''
        ];

        return $postData;

    }

}
